package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
)

func main() {
	http.HandleFunc("/healthz", healthz)
	http.HandleFunc("/", index)
	err := http.ListenAndServe(":8080", logHandler(http.DefaultServeMux))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Server start....")
}

func logHandler(handler http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		//客户端ip
		ip := r.RemoteAddr
		//http返回码
		writer := &MyResponseWriter{}
		writer.ResponseWriter = w
		//将这个自定义的ResponseWriter对象传递给下层的handler.ServeHTTP(writer,r)，这样后面获取的对象就是自定义的Writer，从而可以在Http请求处理过程中记录更多的信息
		handler.ServeHTTP(writer, r)
		//获取返回码
		statusCode := writer.statusCode
		//将ip和返回码输出到标准控制台
		fmt.Printf("IP: %s，Status Code: %d \n", ip, statusCode)
	})
}

/*
*
定义一个新的结构体，结构体包含原生ResponseWriter的引用以及Http返回码
*/
type MyResponseWriter struct {
	http.ResponseWriter
	statusCode int
}

/*
*
重写ResponseWriter.WriteHeader函数
*/
func (w *MyResponseWriter) WriteHeader(statusCode int) {
	//增加记录返回码功能
	w.statusCode = statusCode
	//调用原生ResponseWriter.WriterHeader
	w.ResponseWriter.WriteHeader(statusCode)
}

func healthz(w http.ResponseWriter, r *http.Request) {
	//返回200状态码
	w.WriteHeader(http.StatusOK)
	fmt.Fprintf(w, "OK")
}

func index(w http.ResponseWriter, r *http.Request) {
	header := r.Header
	for key, _ := range header {

		w.Header().Add(key, header.Get(key))
	}
	//加个response header测试下
	w.Header().Add("password", "killer")
	//读取系统环境变量version
	w.Header().Add("VERSION", os.Getenv("VERSION"))
	//返回200状态码
	w.WriteHeader(http.StatusOK)
	fmt.Fprintf(w, "OK")
}
